<template>
  <a-modal
    class="profile-task-dialog formModal editor"
    :class="props.type"
    v-model:open="dialogVisible"
    width="37.5vw"
    :footer="null"
    :title="dialogTitle"
    @cancel="closeDialog"
  >
    <div class="task-publish-modal-content">
      <div class="header">
        1. {{ task_title ? task_title : $t("form.task_fill.sub_title") }}
      </div>
      <a-form layout="vertical" :model="formModel" ref="formRef">
        <!-- publish -->
        <template v-if="type == 'publish'">
          <a-form-item
            :label="$t('form.task_fill.form.item_1.label')"
            name="title"
            :rules="[
              {
                validator: validateTitle,
                trigger: 'blur',
              },
            ]"
            class="span-2"
          >
            <a-input
              :placeholder="$t('form.task_fill.form.item_1.rules.error_1')"
              v-model:value.trim="formModel.title"
              show-count
              :maxlength="30"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="$t('form.task_fill.form.item_category.label')"
            name="category_id"
            :rules="[
              {
                required: true,
                message: $t('form.task_fill.form.item_category.rules.error_1'),
                trigger: 'change',
              },
            ]"
            class="span-2"
          >
            <a-select v-model:value="formModel.category_id">
              <a-select-option
                v-for="item in globalStore.taskCategoryList"
                :value="item.id"
                :key="item.id"
                >{{ item.title }}</a-select-option
              >
            </a-select>
          </a-form-item>

          <a-form-item
            :label="$t('form.task_fill.form.item_2.label')"
            name="content"
            :rules="[
              {
                validator: validateContent,
                trigger: 'blur',
              },
            ]"
          >
            <div style="min-width: 1px" class="flex-1">
              <Editor
                type="modal"
                v-model="formModel.content"
                :placeholder="$t('form.task_fill.form.item_2.rules.error_1')"
              />
            </div>
          </a-form-item>
        </template>
        <template v-if="type == 'follow'">
          <a-form-item
            class="span-2"
            :label="$t('form.task_fill.follow_form.item_1.label')"
            name="title"
            :rules="[
              {
                validator: validateTitle,
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              :placeholder="
                $t('form.task_fill.follow_form.item_1.rules.error_1')
              "
              v-model:value.trim="formModel.title"
              show-count
              :maxlength="30"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="$t('form.task_fill.follow_form.item_2.label')"
            name="content"
            :rules="[
              {
                validator: validateContent,
                trigger: 'blur',
              },
            ]"
          >
            <div style="min-width: 1px" class="flex-1">
              <Editor
                type="modal"
                v-model="formModel.content"
                :placeholder="
                  $t('form.task_fill.follow_form.item_2.rules.error_1')
                "
              />
            </div>
          </a-form-item>
        </template>
        <template v-if="type == 'replay'">
          <a-form-item
            :label="$t('form.task_fill.replay_form.item_1.label')"
            name="content"
            :rules="[
              {
                validator: validateContent,
                trigger: 'blur',
              },
            ]"
          >
            <div style="min-width: 1px" class="flex-1">
              <Editor
                type="modal"
                v-model="formModel.content"
                :placeholder="
                  $t('form.task_fill.replay_form.item_1.rules.error_1')
                "
              />
            </div>
          </a-form-item>
        </template>
      </a-form>
    </div>
    <div class="task-publish-modal-footer">
      <a-button @click="closeDialog">{{ $t("btnText.cancel") }}</a-button>
      <template v-if="type == 'follow' || type == 'replay'">
        <a-button type="primary" @click="continuePublish">{{
          $t("btnText.continue_commit")
        }}</a-button>
      </template>
      <template v-else>
        <a-button type="primary" @click="continuePublish">{{
          $t("btnText.continue_publish")
        }}</a-button>
      </template>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { getCurrentInstance, h, ref, watch } from "vue";
import type { TaskCreateParams } from "../../../types/task";
import { postCreateTask, postTaskFollowUp } from "../../../api/task";
import { postUploadSingleImg } from "../../../api/api";
import { useGlobalStore } from "~/store";
import { message, Modal } from "ant-design-vue";
import { RegLink } from "../../../data/reg";
const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const globalStore = useGlobalStore();

type Props = {
  type?: "follow" | "replay" | "publish";
  id?: string;
  task_title?: string;
};

const props = withDefaults(defineProps<Props>(), {
  type: "publish",
});

const emits = defineEmits(["complete"]);

// =================================================================

const dialogVisible = ref(false);

const dialogTitle = computed(() => {
  let title = $t("form.task_fill.publish_title");
  if (props.type == "follow") {
    title = $t("form.task_fill.follow_title");
  }
  if (props.type == "replay") {
    title = $t("form.task_fill.replay_title");
  }
  return title;
});
const formRef = ref();

const formModel = ref<TaskCreateParams>({
  title: "",
  content: "",
  multi_pic: "",
  file_url: "",
  link_url: "",
  category_id: "",
});

const continuePublish = () => {
  formRef.value.validate().then(() => {
    let okText = $t("btnText.continue_publish");
    if (props.type != "publish") {
      okText = $t("btnText.ensure_commit");
    }
    let modalTitle = $t("dialog.profile_task.confirm_publish");
    if (props.type != "publish") {
      modalTitle = $t("btnText.ensure_commit");
    }
    let modalContent = $t("dialog.profile_task.confirm_desc");
    if (props.type == "replay") {
      modalContent = $t("dialog.profile_task.replay_confirm_desc");
    }
    if (props.type == "follow") {
      modalContent = $t("dialog.profile_task.follow_confirm_desc");
    }
    let confirmModal = Modal.confirm({
      title: modalTitle,
      content: modalContent,
      icon: () => h("", ""),
      centered: true,
      async onOk() {
        let submiting = true;
        confirmModal.update({
          okButtonProps: {
            loading: submiting,
          },
          maskClosable: !submiting,
        });
        let res: any;
        if (props.type == "publish") {
          res = await postCreateTask(formModel.value);
        }
        if (props.type == "follow" || props.type == "replay") {
          formModel.value.task_id = props.id;
          const { category_id, ...params } = formModel.value;
          res = await postTaskFollowUp(params);
        }
        if (res.code === 200) {
          let __msg = $t("message.success.task.create");
          if (props.type == "follow") __msg = $t("message.success.task.follow");
          if (props.type == "replay") __msg = $t("message.success.task.replay");
          message.success(__msg);
          emits("complete");
        } else {
          let __msg = $t("message.error.task.create");
          if (props.type == "follow") __msg = $t("message.error.task.follow");
          if (props.type == "replay") __msg = $t("message.error.task.replay");
          message.error(__msg);
        }
        closeDialog();
        submiting = false;
        confirmModal.update({
          okButtonProps: {
            loading: submiting,
          },
        });
      },
      onCancel() {
      },
      class: "profile-confirm-modal",
      okText,
      cancelText: $t("btnText.back_edit"),
      width: "19.7917vw",
      maskClosable: true,
    });
  });
};

// 弹窗
const showDialog = () => {
  dialogVisible.value = true;
};

const uploadImgRef = ref();
const uploadFileRef = ref();
const closeDialog = () => {
  dialogVisible.value = false;
  formModel.value = {
    title: "",
    content: "",
    multi_pic: "",
    file_url: "",
    link_url: "",
    category_id: "",
  };
  formRef.value.resetFields();
};

defineExpose({
  showDialog,
});

const validateTitle = (_Rule: any, value: string) => {
  if (!value) {
    if (props.type == "publish") {
      return Promise.reject($t("form.task_fill.form.item_1.rules.error_1"));
    }
    if (props.type == "follow") {
      return Promise.reject(
        $t("form.task_fill.follow_form.item_1.rules.error_1")
      );
    }
  }
  return Promise.resolve();
};
const validateContent = (_Rule: any, value: string) => {
  if (!value) {
    if (props.type == "publish") {
      return Promise.reject($t("form.task_fill.form.item_2.rules.error_1"));
    }
    if (props.type == "follow") {
      return Promise.reject(
        $t("form.task_fill.follow_form.item_2.rules.error_1")
      );
    }
    if (props.type == "replay") {
      return Promise.reject(
        $t("form.task_fill.replay_form.item_1.rules.error_1")
      );
    }
    return;
  }
  return Promise.resolve();
};
</script>

<style lang="less">
.profile-task-dialog.follow,
.profile-task-dialog.publish {
  .ant-modal-content .ant-form .ant-form-item:first-child .ant-input {
    padding: 0;
    height: auto;
  }
}
</style>

<style scoped lang="less">
.task-publish-modal-content {
  margin-top: 20px;
  .header {
    padding: 12px 8px;
    margin-bottom: 24px;
    color: #fff;
    background: #3d88f2;
    font-size: 18px;
  }
}
.task-publish-modal-footer {
  padding: 24px 0;
  padding-bottom: 0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  .ant-btn {
    height: 40px !important;
    border-radius: 10px !important;
    font-size: 14px !important;
  }
}
</style>
